import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/base/application.dart';
import 'package:panda/entity/good_list_entity.dart';
import 'package:panda/goods/GoodsDetail.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/SignUtil.dart';

import '../base/Constant.dart';

class SelectTopGoodsPage extends StatefulWidget {
  int type = 0;
  SelectTopGoodsPage({Key key, this.type}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return SelectTopGoodsView();
  }
}

class SelectTopGoodsView extends State<SelectTopGoodsPage> {
  List<GoodsListDataData> goodsList = new List();
  int page = 1;
  String group_id = "1";
  String name = "";
  String token = "";
  EasyRefreshController _controller = EasyRefreshController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
      // loadList();
    });
    if (APPLIC.userInfoMap != null)
      group_id = APPLIC.userInfoMap['user_msg']['group_id'].toString();
    loadList();
  }

  loadList() async {
    Map map = new Map();
    map['goods_name'] = name;
    map['p'] = page.toString();
    map['per'] = "10";
    map['cat_id'] = widget.type == 9 ? "7" : "5";
    map['sign_type'] = SignType.GET_GOODS_LIST;
    Response<String> response =
        await HttpUtil().post(Api.GET_GOODS_LIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    if (userMap['code'] == 1 && mounted) {
      GoodsListEntity bannerEntity = new GoodsListEntity.fromJson(userMap);
      setState(() {
        if (page == 1) {
          goodsList.clear();
        }
        if (page == 1) {
          _controller.resetLoadState();
          _controller.finishRefresh();
        } else {
          _controller.finishLoad(
              success: true, noMore: bannerEntity.data.datas.length == 0);
          if (bannerEntity.data.datas.length == 0) {
            Fluttertoast.showToast(msg: "已加载全部");
          }
        }
        goodsList.addAll(bannerEntity.data.datas);
        setState(() {});
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

    return new Scaffold(
      appBar: new AppBar(
        title: Text(
            widget.type == 9 ? '品牌馆' : widget.type == 1 ? "0元购" : '熊猫自营',
            style: TextStyle(
                fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                color: Colors.black)),
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
        elevation: 0.5,
      ),
      body: new Container(
        color: white,
        child: Column(
          children: <Widget>[
            Expanded(
                child: new EasyRefresh(
              enableControlFinishRefresh: true,
              enableControlFinishLoad: true,
              header: MaterialHeader(),
              footer: MaterialFooter(),
              controller: _controller,
              child: ListView.builder(
                  itemBuilder: _renderRow, itemCount: goodsList.length),
              onRefresh: () async {
                page = 1;
                loadList();
              },
              onLoad: () async {
                page++;
                loadList();
              },
            ))
          ],
        ),
      ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    return GestureDetector(
      child: Container(
        margin: EdgeInsets.fromLTRB(
            ScreenUtil.getInstance().setHeight(DP_20),
            ScreenUtil.getInstance().setHeight(DP_20),
            ScreenUtil.getInstance().setHeight(DP_20),
            0),
        decoration: BoxDecoration(
            color: white,
            borderRadius: BorderRadius.circular(
                ScreenUtil.getInstance().setHeight(DP_10))),
        child: Material(
          borderRadius:
              BorderRadius.circular(ScreenUtil.getInstance().setHeight(DP_10)),
          color: white,
          child: new Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
             Stack(
              children: <Widget>[
                ClipRRect(
                  borderRadius: BorderRadius.only(
                      topRight: Radius.circular(
                          ScreenUtil.getInstance().setHeight(DP_10)),
                      topLeft: Radius.circular(
                          ScreenUtil.getInstance().setHeight(DP_10))),
                  child: CachedNetworkImage(
                      imageUrl: Api.ImgBaseUrl + goodsList[index].img,
                      width: (MediaQuery.of(context).size.width +
                          40 -
                          ScreenUtil.getInstance().setHeight(DP_40)),
                      fit: BoxFit.cover,
                      height: (MediaQuery.of(context).size.width +
                              40 -
                              ScreenUtil.getInstance().setHeight(DP_40)) *
                          0.45),
                ),
                Offstage(
                  child: Container(
                      alignment: Alignment.center,
                      child: Text(
                        '已售罄',
                        style: TextStyle(color: white, fontSize: 13),
                      ),
                      decoration: BoxDecoration(
                          color: Color.fromARGB(125, 0, 0, 0),
                          borderRadius: BorderRadius.only(
                              topRight: Radius.circular(
                                  ScreenUtil.getInstance().setHeight(DP_10)),
                              topLeft: Radius.circular(
                                  ScreenUtil.getInstance().setHeight(DP_10)))),
                      width: (MediaQuery.of(context).size.width +
                          40 -
                          ScreenUtil.getInstance().setHeight(DP_40)),
                      height: 0.45 *
                          (MediaQuery.of(context).size.width +
                              40 -
                              ScreenUtil.getInstance().setHeight(DP_40))),
                  offstage: (int.parse(goodsList[index].sales_volume) +
                              int.parse(goodsList[index].virtual_volume)) >=
                          int.parse(goodsList[index].num)
                      ? false
                      : true,
                )
              ],
            ),
           Padding(
                padding: EdgeInsets.fromLTRB(
                    ScreenUtil.getInstance().setHeight(DP_15),
                    ScreenUtil.getInstance().setHeight(DP_15),
                    ScreenUtil.getInstance().setHeight(DP_15),
                    ScreenUtil.getInstance().setHeight(DP_8)),
                child: Text(
                  goodsList[index].goods_name,
                  style: TextStyle(
                      fontSize:
                          ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                      color: black),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              Row(children: <Widget>[
                Expanded(
                    child: Column(children: <Widget>[
                  Padding(
                    padding: EdgeInsets.fromLTRB(
                        ScreenUtil.getInstance().setHeight(DP_15),
                        0,
                        ScreenUtil.getInstance().setHeight(DP_15),
                        ScreenUtil.getInstance().setHeight(DP_15)),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: <Widget>[
                        Text('团购价' + MONEY,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(MINI_FONT_SIZE),
                                color: black_99)),
                        Text(goodsList[index].price.toString(),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(NORMAL_FONT_SIZE),
                                color: black)),
                        // Expanded(
                        //   child: Text(''),
                        //   flex: 1,
                        // ),
                        Text('    市场价$MONEY',
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(MINI_FONT_SIZE),
                                color: black_99)),
                        Text(goodsList[index].old_price.toString(),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(NORMAL_FONT_SIZE - 3),
                                color: black)),
                      ],
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.fromLTRB(
                        ScreenUtil.getInstance().setHeight(DP_15),
                        0,
                        ScreenUtil.getInstance().setHeight(DP_15),
                        ScreenUtil.getInstance().setHeight(DP_15)),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        SizedBox(
                          width: ScreenUtil.getInstance().setHeight(25) *
                                  goodsList[index].avatars.length.toDouble() +
                              12,
                          child: Stack(
                              alignment: AlignmentDirectional.topStart,
                              children: buildAvatar(goodsList[index].avatars)),
                        ),
                        Container(
                            width: ScreenUtil.getInstance().setHeight(DP_15)),
                        Text(
                            (int.parse(goodsList[index].sales_volume) +
                                        int.parse(
                                            goodsList[index].virtual_volume))
                                    .toString() +
                                '人已购',
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE - 2),
                                color: Colors.black45)),
                        // Expanded(
                        //   child: Center(),
                        // ),
                      ],
                    ),
                  )
                ])),
                (int.parse(goodsList[index].sales_volume) +
                            int.parse(goodsList[index].virtual_volume)) >=
                        int.parse(goodsList[index].num)
                    ? new Container(
                        color: Colors.grey[300],
                        margin: EdgeInsets.only(right: 10),
                        padding: EdgeInsets.fromLTRB(10, 5, 10, 2),
                        child: Text("已售罄",
                            style: TextStyle(
                                color: white,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE))),
                      )
                    : Column(children: <Widget>[
                        new Container(
                          height: ScreenUtil.getInstance().setWidth(DP_40),
                          margin: EdgeInsets.only(right: 10),
                          alignment: Alignment.center,
                          width: ScreenUtil.getInstance().setWidth(DP_160),
                          decoration: new BoxDecoration(
                              color: Colors.white,
                              border: Border.all(width: 1, color: mainColor),
                              borderRadius: BorderRadius.only(
                                  topLeft: Radius.circular(3),
                                  topRight: Radius.circular(3))),
                          child: new Padding(
                            padding: EdgeInsets.only(left: 10.0, right: DP_10),
                            child: new Text(
                              (int.parse(goodsList[index].sales_volume) +
                                          int.parse(goodsList[index]
                                              .virtual_volume)) >=
                                      int.parse(goodsList[index].num)
                                  ? "售罄"
                                  : "限" + goodsList[index].num + "份",
                              style: new TextStyle(
                                  color: mainColor,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(SMALL_FONT_SIZE - 2)),
                            ),
                          ),
                        ),
                        new Container(
                          height: ScreenUtil.getInstance().setWidth(DP_40),
                          margin: EdgeInsets.only(right: 10),
                          alignment: Alignment.center,
                          width: ScreenUtil.getInstance().setWidth(DP_160),
                          decoration: new BoxDecoration(
                              color: mainColor,
                              borderRadius: BorderRadius.only(
                                  bottomLeft: Radius.circular(3),
                                  bottomRight: Radius.circular(3))),
                          child: new Padding(
                            padding: EdgeInsets.only(left: 10.0, right: DP_10),
                            child: new Text(
                              "立即购买",
                              style: new TextStyle(
                                  color: Colors.white,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(SMALL_FONT_SIZE - 2)),
                            ),
                          ),
                        )
                      ])
              ])
            ],
          ),
          elevation: 1,
        ),
      ),
      onTap: () {
        if ((int.parse(goodsList[index].sales_volume) +
                int.parse(goodsList[index].virtual_volume)) >=
            int.parse(goodsList[index].num)) {
          Fluttertoast.showToast(msg: '亲宝贝已经售馨，下次早抢哦！');

          return;
        }
        Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
          return GoodsDetailPage(
            goods_id: goodsList[index].goods_id,
            img: goodsList[index].img,
          );
        }));
      },
    );
  }

  buildAvatar(List<GoodsListDataDatasTag> avatars) {
    List<Widget> list = new List();
    list.add(ClipOval(
      child: CachedNetworkImage(
          imageUrl: Api.ImgBaseUrl + avatars[0].avatar,
          width: ScreenUtil.getInstance().setHeight(35),
          height: ScreenUtil.getInstance().setHeight(35)),
    ));
    for (int i = 1; i < avatars.length; i++) {
      list.add(
        Positioned(
          left: ScreenUtil.getInstance().setHeight(25) * i.toDouble(),
          child: ClipOval(
            child: CachedNetworkImage(
                imageUrl: Api.ImgBaseUrl + avatars[i].avatar,
                width: ScreenUtil.getInstance().setHeight(35),
                height: ScreenUtil.getInstance().setHeight(35)),
          ),
        ),
      );
    }
    return list;
  }
}
